#include<iostream>
#include<vector>
#include<map>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* recur(vector<int>& preorder, int pl,int pr, vector<int>& inorder,int il,int ir, map<int,int>& idx)
{
    TreeNode* h = nullptr;
    if(pl<pr && il<ir)
    {
        h = new TreeNode(preorder[pl]);
        int id = idx[h->val];
        h->left = recur(preorder,pl+1,pl+id-il+1,inorder,il,id, idx);
        h->right = recur(preorder,pl+id-il+1,pr,inorder,id+1,ir, idx);
    }
    return h;
}

class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        // build idx: val->inorder_id
        map<int,int> idx;
        for(int i = 0;i<inorder.size();++i)
            idx[inorder[i]] = i;
        int N = preorder.size();
        TreeNode* res = recur(preorder,0,N,inorder,0,N,idx);
        return res;
    }
};

int main(int argc, char const *argv[])
{
    freopen("test.txt","r",stdin);
    int N; cin>>N;
    vector<int> preorder(N),inorder(N);
    for(int i = 0;i<N;++i) cin>>preorder[i];
    for(int i = 0;i<N;++i) cin>>inorder[i];

    Solution sol;
    TreeNode* h = sol.buildTree(preorder,inorder);

    return 0;
}

